package com.xh.one2one.lesson.service.impl;

import com.xh.bussiness.thirdapi.xinzhou.bean.request.XzGroupScheduleRequest;
import com.xh.bussiness.thirdapi.xinzhou.bean.request.XzScheduleRequest;
import com.xh.bussiness.thirdapi.xinzhou.bean.request.XzStudentInfoRequest;
import com.xh.bussiness.thirdapi.xinzhou.model.XzGroupSchedule;
import com.xh.bussiness.thirdapi.xinzhou.model.XzRemainContactHour;
import com.xh.bussiness.thirdapi.xinzhou.model.XzSchedule;
import com.xh.bussiness.thirdapi.xinzhou.service.IXinzhouTmsService;
import com.xh.core.util.DateUtils;
import com.xh.core.util.StringUtils;
import com.xh.core.util.UserUtils;
import com.xh.one2one.base.model.StudentInfo;
import com.xh.one2one.lesson.bean.dto.LessonInfoDto;
import com.xh.one2one.lesson.bean.dto.LessonSummaryDto;
import com.xh.one2one.lesson.bean.request.LessonInfoRequest;
import com.xh.one2one.lesson.bean.request.LessonSummaryRequest;
import com.xh.one2one.lesson.bean.request.LessonTimesRequest;
import com.xh.one2one.lesson.model.*;
import com.xh.one2one.lesson.dao.LessonInfoMapper;
import com.xh.one2one.lesson.service.*;
import com.xh.core.service.impl.BaseServiceImpl;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.core.bean.XhPage;
import org.springframework.util.CollectionUtils;


import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

/**
 * <p>
 * 一对一备课 服务实现类
 * </p>
 *
 * @author tw
 * @since 2021-04-07
 */
@Service
public class LessonInfoServiceImpl extends BaseServiceImpl<LessonInfoMapper, LessonInfo> implements ILessonInfoService {

    Logger log = LoggerFactory.getLogger(LessonInfoServiceImpl.class);

    @Autowired
    private IXinzhouTmsService xinzhouTmsService;
    @Autowired
    private ILessonSummaryService summaryService;
    @Autowired
    private ILessonSummaryDetailsService summaryDetailsService;
    @Autowired
    private ILessonTimesService timesService;
    @Autowired
    private ILessonHomeworkService homeworkService;
    @Autowired
    private ILessonEntranceExamService examService;
    @Autowired
    private ILessonPlanService lessonPlanService;


    @Override
    public XhPage queryLessonInfoPage(XhPage page, LessonInfoRequest bean) {
        QueryWrapper qw = new QueryWrapper<LessonInfo>();
        //拼装条件
        qw = prepareParams(bean, qw);

        return (XhPage) this.dao.selectPage(page, qw);
    }

//    @Override
//    public List queryLessonInfo(LessonInfoRequest bean) {
//        Integer searchType = bean.getSearchType();
//        //查询小组课排课
//        XzGroupScheduleRequest groupScheduleRequest = new XzGroupScheduleRequest();
//        groupScheduleRequest.setTeacherid(bean.getUserId());
//        groupScheduleRequest.setClassDateTimeFrom_begin(bean.getStartDate().replaceAll("/", "-"));
//        groupScheduleRequest.setClassDateTimeFrom_end(bean.getEndDate().replaceAll("/", "-"));
//        List<XzGroupSchedule> groups = new ArrayList<>();
//        if (searchType == 0 || searchType == 2) {
//            groups = xinzhouTmsService.querySchedule(groupScheduleRequest);
//        }
//        //查询一对一排课
//        XzScheduleRequest scheduleRequest = new XzScheduleRequest();
//        BeanUtils.copyProperties(groupScheduleRequest, scheduleRequest);
//        scheduleRequest.setScheduleInstanceOTOType("一对一");
//        List<XzSchedule> schedules = new ArrayList<>();
//        if (searchType == 0 || searchType == 1) {
//            schedules = xinzhouTmsService.querySchedule(scheduleRequest);
//        }
//
//        List<LessonInfoDto> ret = new ArrayList<>();
//        List<LessonInfo> updateList = new ArrayList<>();
//        groups.forEach(xzGroupSchedule -> {
//            //排除掉还没有学生加入到当前课次的排课数据
//            if (xzGroupSchedule.getStudentCount() > 0) {
//                LessonInfoDto dto = new LessonInfoDto();
//                String thirdId = xzGroupSchedule.getGroupOTOInstanceId();
//                String groupId = xzGroupSchedule.getGroupId();
//                String contractOTOId = xzGroupSchedule.getContractOTOId();
//                dto.setThirdId(thirdId);
//                dto.setLessonId(groupId);
//                dto.setContractId(contractOTOId);
//                dto.setSubjectName(xzGroupSchedule.getSubject());
//                dto.setLessonName(xzGroupSchedule.getGroupName());
//                dto.setStartDate(DateUtils.format(xzGroupSchedule.getClassDateTimeFrom(), "yyyy-MM-dd HH:mm:ss"));
//                dto.setEndDate(DateUtils.format(xzGroupSchedule.getClassDateTimeTo(), "yyyy-MM-dd HH:mm:ss"));
//                dto.setStatus(0);
//                dto.setStep(1);
//                dto.setType(2);
//                LessonInfo byLessonId = getByThirdId(thirdId);
//                if (null == byLessonId) {
//                    LessonInfo li = new LessonInfo();
//                    li.setLessonId(groupId);
//                    li.setThirdId(thirdId);
//                    li.setContractId(contractOTOId);
//                    li.setLessonName(xzGroupSchedule.getGroupName());
//                    li.setType(2);
//                    li.setStatus(0);
//                    li.setStep(1);
//                    li.setStartTime(xzGroupSchedule.getClassDateTimeFrom());
//                    li.setEndTime(xzGroupSchedule.getClassDateTimeTo());
//                    this.insert(li);
//                    dto.setId(li.getId());
//                } else {
//                    dto.setId(byLessonId.getId());
//                    dto.setStatus(byLessonId.getStatus());
//                    dto.setStep(byLessonId.getStep());
//                    //小组课会修改名称
//                    byLessonId.setLessonName(xzGroupSchedule.getGroupName());
//                    updateList.add(byLessonId);
//                }
//                ret.add(dto);
//            }
//        });
//
//        schedules.forEach(schedule -> {
//            LessonInfoDto dto = new LessonInfoDto();
//            String thirdId = schedule.getScheduleInstanceOTOId();
//            String groupId = schedule.getStudentId();
//            String contractOTOId = schedule.getContractOTOId();
//            dto.setThirdId(thirdId);
//            dto.setLessonId(groupId);
//            dto.setContractId(contractOTOId);
//            dto.setLessonName(schedule.getStudentName());
//            dto.setSubjectName(schedule.getScheduleInstanceOTOSubject());
//            dto.setStartDate(DateUtils.format(schedule.getClassDateTimeFrom(), "yyyy-MM-dd HH:mm:ss"));
//            dto.setEndDate(DateUtils.format(schedule.getClassDateTimeTo(), "yyyy-MM-dd HH:mm:ss"));
//            dto.setStatus(0);
//            dto.setStep(1);
//            dto.setType(1);
//            LessonInfo byLessonId = getByThirdId(thirdId);
//
//            if (null == byLessonId) {
//                LessonInfo li = new LessonInfo();
//                li.setLessonId(groupId);
//                li.setLessonName(schedule.getStudentName());
//                li.setThirdId(thirdId);
//                li.setContractId(contractOTOId);
//                li.setType(1);
//                li.setStatus(0);
//                li.setStep(1);
//                li.setStartTime(schedule.getClassDateTimeFrom());
//                li.setEndTime(schedule.getClassDateTimeTo());
//                this.insert(li);
//                dto.setId(li.getId());
//            } else {
//                dto.setId(byLessonId.getId());
//                dto.setStatus(byLessonId.getStatus());
//                dto.setStep(byLessonId.getStep());
//                byLessonId.setLessonName(schedule.getStudentName());
//                byLessonId.setContractId(contractOTOId);
//                updateList.add(byLessonId);
//            }
//            ret.add(dto);
//        });
//
//        //批量更新
//        if (!CollectionUtils.isEmpty(updateList)) {
//            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
//                this.batchUpdate(updateList);
//            });
//        }
//
//        List<LessonInfoDto> resultList = ret.stream().collect(collectingAndThen(toCollection(
//                () -> new TreeSet<>(
//                        Comparator.comparing(LessonInfoDto::getThirdId))), ArrayList::new));
//
//        resultList = resultList.stream().sorted(Comparator.comparing(LessonInfoDto::getStartDate)).collect(Collectors.toList());
//
//        return resultList;
//
//    }

    public List queryLessonInfo(LessonInfoRequest bean) {
        List<LessonPlan> plans = lessonPlanService.queryByList(bean);
        List<LessonInfoDto> resultList = new ArrayList<>(plans.size());
        for (LessonPlan plan : plans) {
            LessonInfoDto infoDto = new LessonInfoDto();
            infoDto.setSubjectName(plan.getSubjectName());
            infoDto.setLessonId(plan.getId());
            infoDto.setThirdId(plan.getId());
            infoDto.setLessonName(plan.getStudentNames());
            infoDto.setStartDate(DateUtils.format(plan.getLessonTime(), "yyyy-MM-dd HH:mm:ss"));
            infoDto.setType(2);
            infoDto.setStatus(0);
            infoDto.setStep(1);
            LessonInfo info = getByThirdId(plan.getId());
            if(info != null){
                infoDto.setId(info.getId());
                infoDto.setStep(info.getStep());
                infoDto.setStatus(info.getStatus());
            }else{
                LessonInfo li = new LessonInfo();
                li.setLessonId(plan.getId());
                li.setThirdId(plan.getId());
                li.setLessonName(plan.getSubjectName());
                li.setType(2);
                li.setStatus(0);
                li.setStep(1);
                this.insert(li);
                infoDto.setId(li.getId());
            }
            resultList.add(infoDto);
        }
        return resultList;
    }

    @Override
    public List queryStudentOrGroups(LessonInfoRequest bean) throws Exception {
        Integer searchType = bean.getSearchType();
        //查询小组课排课
        XzGroupScheduleRequest groupScheduleRequest = new XzGroupScheduleRequest();
        groupScheduleRequest.setTeacherid(bean.getUserId());

        List<XzGroupSchedule> groups = new ArrayList<>();
        if (searchType == 2) {
            Date now = DateUtils.getTodayDate();
            Date startDate = org.apache.commons.lang.time.DateUtils.addMonths(now, -3);
            Date endDate = org.apache.commons.lang.time.DateUtils.addMonths(now, 1);
            String startDateStr = DateUtils.format(startDate, "yyyy-MM-dd");
            String endDateStr = DateUtils.format(endDate, "yyyy-MM-dd");

            groupScheduleRequest.setClassDateTimeFrom_begin(startDateStr);
            groupScheduleRequest.setClassDateTimeFrom_end(endDateStr);
            groups = xinzhouTmsService.querySchedule(groupScheduleRequest);
        }

        List<XzSchedule> schedules = new ArrayList<>();
        if (searchType == 1) {
            //查询一对一排课
            XzScheduleRequest scheduleRequest = new XzScheduleRequest();
            BeanUtils.copyProperties(groupScheduleRequest, scheduleRequest);
            scheduleRequest.setScheduleInstanceOTOType("一对一");
            schedules = xinzhouTmsService.querySchedule(scheduleRequest);
        }
        List<LessonInfoDto> ret = new ArrayList<>();

        if (!CollectionUtils.isEmpty(groups)) {
            List<XzGroupSchedule> groupList = groups.stream().collect(collectingAndThen(toCollection(
                    () -> new TreeSet<>(
                            Comparator.comparing(XzGroupSchedule::getGroupId))), ArrayList::new));

            groupList.forEach(xzGroupSchedule -> {
                LessonInfoDto dto = new LessonInfoDto();
                String thirdId = xzGroupSchedule.getGroupOTOInstanceId();
                String groupId = xzGroupSchedule.getGroupId();
                String contractId = xzGroupSchedule.getContractOTOId();
                dto.setThirdId(thirdId);
                dto.setLessonId(groupId);
                dto.setContractId(contractId);
                dto.setSubjectName(xzGroupSchedule.getSubject());
                dto.setLessonName(xzGroupSchedule.getGroupName());
                dto.setStartDate(DateUtils.format(xzGroupSchedule.getClassDateTimeFrom(), "yyyy-MM-dd HH:mm:ss"));
//                dto.setEndDate(DateUtils.format(xzGroupSchedule.getClassDateTimeTo(),"yyyy-MM-dd HH:mm:ss"));
//                dto.setStatus(0);
//                dto.setStep(1);
//                dto.setType(2);
                LessonInfo byLessonId = getByThirdId(thirdId);
                //没有排课信息，排除
                if (null != byLessonId) {
                    dto.setId(byLessonId.getId());
                    ret.add(dto);
                }

            });
        }

        if (!CollectionUtils.isEmpty(schedules)) {

            List<LessonInfoDto> students = new ArrayList<>();
            Map<String, Boolean> cacheRemainMap = new HashMap<>();
            for (XzSchedule schedule : schedules) {
                String thirdId = schedule.getScheduleInstanceOTOId();
                String groupId = schedule.getStudentId();
                String contractId = schedule.getContractOTOId();

                Boolean checked = MapUtils.getBoolean(cacheRemainMap, groupId);
                if (null == checked) {
                    checked = checkRemainHours(cacheRemainMap, groupId);
                }
                if (checked) {
                    continue;
                }
                LessonInfoDto dto = new LessonInfoDto();
                dto.setThirdId(thirdId);
                dto.setLessonId(groupId);
                dto.setContractId(contractId);
                dto.setLessonName(schedule.getStudentName());
                dto.setSubjectName(schedule.getScheduleInstanceOTOSubject());
                dto.setStartDate(DateUtils.format(schedule.getClassDateTimeFrom(), "yyyy-MM-dd HH:mm:ss"));
//            dto.setEndDate(DateUtils.format(schedule.getClassDateTimeTo(),"yyyy-MM-dd HH:mm:ss"));
//            dto.setStatus(0);
//            dto.setStep(1);
//            dto.setType(1);
                LessonInfo byLessonId = getByThirdId(thirdId);
                //没有排课信息，排除
                if (null == byLessonId) {
                    continue;
                }
                dto.setId(byLessonId.getId());
                students.add(dto);
            }
            //去重
            students = students.stream().collect(collectingAndThen(toCollection(
                    () -> new TreeSet<>(
                            Comparator.comparing(LessonInfoDto::getLessonId))), ArrayList::new));
            ret.addAll(students);
        }

        List resultList = ret.stream().sorted(Comparator.comparing(LessonInfoDto::getStartDate)).collect(Collectors.toList());


        return resultList;

    }

    private boolean checkRemainHours(Map<String, Boolean> cacheRemainMap, String groupId) throws Exception {
        XzStudentInfoRequest studentRequest = new XzStudentInfoRequest();
        studentRequest.setStudentId(groupId);
        List<XzRemainContactHour> hours = xinzhouTmsService.queryStudentRemainContactHour(studentRequest);
        if (CollectionUtils.isEmpty(hours)) {
            cacheRemainMap.put(groupId, true);
            return true;
        }
        if (!CollectionUtils.isEmpty(hours)) {
            long count = hours.stream().filter(data -> data.getContractType().equals("一对一") && data.getRemainCount() > 0).count();
            if (count == 0) {
                cacheRemainMap.put(groupId, true);
                return true;
            }
        }
        cacheRemainMap.put(groupId, false);
        return false;
    }

    @Override
    public List queryStudent(LessonInfoRequest bean) {
//        //查询排课学生
//        XzScheduleRequest scheduleRequest = new XzScheduleRequest();
//        if (1 == bean.getSearchType()) {
//            scheduleRequest.setStudentId(bean.getLessonId());
//            scheduleRequest.setScheduleInstanceOTOType("一对一");
//        } else {
//            scheduleRequest.setGroupId(bean.getLessonId());
//            scheduleRequest.setScheduleInstanceOTOType("一对六");
//        }
//
//        boolean emptyId = StringUtils.isEmpty(bean.getId());
//        Date startTime = null;
//        Date endTime = null;
//        if (!emptyId) {
//            LessonInfo lessonInfo = this.getById(bean.getId());
//            if (null != lessonInfo) {
//                startTime = lessonInfo.getStartTime();
//                endTime = lessonInfo.getEndTime();
//            }
//        }
//
//        if (null != startTime) {
//            scheduleRequest.setClassDateTimeFrom_begin(DateUtils.format(startTime, "yyyy-MM-dd"));
//        } else {
//            scheduleRequest.setClassDateTimeFrom_begin(bean.getStartDate());
//        }
//        if (null != endTime) {
//            scheduleRequest.setClassDateTimeFrom_end(DateUtils.format(endTime, "yyyy-MM-dd"));
//        } else {
//            scheduleRequest.setClassDateTimeFrom_end(bean.getEndDate());
//        }
//        List<XzSchedule> schedules = xinzhouTmsService.querySchedule(scheduleRequest);
//        if (CollectionUtils.isEmpty(schedules)) {
//            return Collections.EMPTY_LIST;
//        }
//
//        if (null != startTime) {
//            final Date startDate = startTime;
//            schedules = schedules.stream().filter(schedule -> schedule.getClassDateTimeFrom().equals(startDate)).collect(Collectors.toList());
//        }
//
//        List retList = schedules.stream().sorted(Comparator.comparing(XzSchedule::getClassDateTimeFrom, (x, y) -> {
//            if (x.equals(y)) {
//                return 0;
//            }
//            boolean flag = x.before(y);
//            if (flag) {
//                return -1;
//            } else {
//                return 1;
//            }
//        })).collect(collectingAndThen(
//                toCollection(() -> new TreeSet<>(Comparator.comparing(XzSchedule::getStudentId))), ArrayList::new));
        List<XzSchedule> schedules = new ArrayList<>();
        LessonPlan lessonPlan = lessonPlanService.getById(bean.getLessonId());
        String studentIds = lessonPlan.getStudentIds();
        String studentNames = lessonPlan.getStudentNames();
        if(StringUtils.isNotEmpty(studentIds)){
            List<String> ids = Arrays.asList(studentIds.split(","));
            List<String> names = Arrays.asList(studentNames.split(","));
            for (int i = 0; i < ids.size(); i++) {
                XzSchedule schedule = new XzSchedule();
                schedule.setStudentId(ids.get(i));
                schedule.setStudentName(names.get(i));
                schedules.add(schedule);
            }
        }
        return schedules;
    }

    @Override
    public List queryLessons(LessonInfoRequest bean) throws Exception {
//        QueryWrapper qw = new QueryWrapper<LessonInfo>();
//        //拼装条件
//        qw.eq("creator_id", bean.getUserId());
////       qw.ge("end_time",DateUtils.parse(bean.getStartDate(),"yyyy-MM-dd HH:mm:ss"));
////       qw.le("end_time",DateUtils.parse(bean.getEndDate(),"yyyy-MM-dd HH:mm:ss"));
//        if (1 == bean.getSearchType()) {
//            qw.eq("type", 1);
//        } else {
//            qw.eq("type", 2);
//        }
//        qw.groupBy("lesson_id");
//        List<LessonInfo> list = this.dao.selectList(qw);
//        if (1 == bean.getSearchType()) {
//            Iterator<LessonInfo> iterator = list.iterator();
//            while (iterator.hasNext()) {
//                LessonInfo lessonInfo = iterator.next();
//                String lessonId = lessonInfo.getLessonId();
//                if (!checkStudent(lessonId)) {
//                    iterator.remove();
//                }
//            }
//        }
//        return list;
        QueryWrapper<LessonPlan> qw = new QueryWrapper<>();
        qw.eq("teacher_id", UserUtils.getCurrentUserId());
        List<LessonPlan> list = lessonPlanService.queryByCondition(qw);
        List<String> ids = new ArrayList<>();
        List<LessonInfo> infos = new ArrayList<>();
        for (LessonPlan lessonPlan : list) {
            String stuIdsStr = lessonPlan.getStudentIds();
            if(StringUtils.isNotEmpty(stuIdsStr)){
                String[] stuIds = stuIdsStr.split(",");
                String[] stuNames = lessonPlan.getStudentNames().split(",");
                for (int i = 0; i < stuIds.length; i++) {
                    if(!ids.contains(stuIds[i])){
                        LessonInfo info = new LessonInfo();
                        info.setLessonId(stuIds[i]);
                        info.setLessonName(stuNames[i]);
                        infos.add(info);
                        ids.add(stuIds[i]);
                    }
                }
            }
        }
        return infos;
    }

    public boolean checkStudent(String lessonId) throws Exception {
        XzStudentInfoRequest studentInfo = new XzStudentInfoRequest();
        studentInfo.setStudentId(lessonId);
        List<XzRemainContactHour> contactHour = xinzhouTmsService.queryStudentRemainContactHour(studentInfo);
        for (int j = 0; j < contactHour.size(); j++) {
            XzRemainContactHour xzRemainContactHour = contactHour.get(j);
            if ("一对一".equals(xzRemainContactHour.getContractType())) {
                if (xzRemainContactHour.getRemainCount() > 0) {
                    return true;
                }
            }
        }
        return false;
    }


    @Override
    public List queryLessonAndStudent(LessonInfoRequest bean) throws Exception {
        List<LessonInfoDto> dtoList = new ArrayList<>();
        List<LessonInfo> list = queryLessons(bean);
        list.forEach(lessonInfo -> {
            String lessonId = lessonInfo.getLessonId();
            bean.setLessonId(lessonId);
            List<XzSchedule> students = queryStudent(bean);
            List<StudentInfo> studentInfoList = new ArrayList<>();
            students.forEach(xzSchedule -> {
                StudentInfo studentInfo = new StudentInfo();
                studentInfo.setStudentId(xzSchedule.getStudentId());
                studentInfo.setStudentName(xzSchedule.getStudentName());
                studentInfoList.add(studentInfo);
            });
            LessonInfoDto dto = new LessonInfoDto();
            BeanUtils.copyProperties(lessonInfo, dto);
            dto.setStudents(studentInfoList);
            dtoList.add(dto);
        });
        return dtoList;
    }


    @Override
    public LessonInfo getByThirdId(String thirdId) {
        QueryWrapper qw = new QueryWrapper<LessonInfo>();
        //拼装条件
        qw.eq("third_id", thirdId);

        return this.selectFirst(qw);
    }


    @Override
    public XhPage queryStudentEvaluate(XhPage page, LessonInfoRequest bean) {
        //查询当前老师的已通过的课
        QueryWrapper<LessonInfo> lessonInfoQW = new QueryWrapper<>();
        lessonInfoQW.eq("creator_id", UserUtils.getCurrentUserId());
        lessonInfoQW.eq("status", 3);
        //排课方式
        if (bean.getSearchType() != null && bean.getSearchType() != 0) {
            lessonInfoQW.eq("type", bean.getSearchType());
        }
        //上课时间
        if (StringUtils.isNotEmpty(bean.getStartDate()) && StringUtils.isNotEmpty(bean.getEndDate())) {
            lessonInfoQW.ge("start_time", bean.getStartDate());
            lessonInfoQW.le("end_time", bean.getEndDate());
        }
        lessonInfoQW.orderByDesc("start_time");
        XhPage<LessonInfo> lessonInfoPage = (XhPage) this.selectPage(page, lessonInfoQW, LessonInfo.class);
        //根据课程 third_id 查询学生评价状态
        List<LessonInfoDto> infoDtos = new ArrayList<>();
        XhPage xhPage = new XhPage();
        xhPage.setTotal(lessonInfoPage.getTotal());
        xhPage.setCurrent(lessonInfoPage.getCurrent());
        xhPage.setSize(page.getSize());
        xhPage.setRecords(infoDtos);
        List<LessonInfo> lessonInfos = lessonInfoPage.getRecords();
        for (LessonInfo lessonInfo : lessonInfos) {
            Integer type = lessonInfo.getType();
            LessonInfoDto infoDto = new LessonInfoDto();
            infoDto.setId(lessonInfo.getId());
            infoDto.setLessonId(lessonInfo.getLessonId());
            infoDto.setContractId(lessonInfo.getContractId());
            infoDto.setThirdId(lessonInfo.getThirdId());
            infoDto.setStartDate(DateUtils.format(lessonInfo.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
            infoDto.setEndDate(DateUtils.format(lessonInfo.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
            infoDto.setLessonName(lessonInfo.getLessonName());
            infoDto.setType(type);

            if (type == 2) {
                //小组课需要计算已评价人 和 学生总数 并设置评价状态
                LessonInfoDto lessonInfoDto = summaryService.queryGroupClassEvaluate(lessonInfo);
                infoDto.setEvaluateStatus(lessonInfoDto.getStudentCount() == lessonInfoDto.getEvaluated() ? 1 : 0);
                infoDto.setStudentCount(lessonInfoDto.getStudentCount());
                infoDto.setEvaluated(lessonInfoDto.getEvaluated());
            }

            QueryWrapper<LessonSummary> lessonSummaryQW = new QueryWrapper<>();
            lessonSummaryQW.eq("lesson_third_id", lessonInfo.getThirdId());
            if (bean.getStatus() != 3) {
                lessonSummaryQW.eq("status", bean.getStatus()); // 是否已评价（0 否  1 是）
            }
            List<LessonSummary> summaries = summaryService.selectList(lessonSummaryQW, LessonSummary.class);

            List<LessonSummaryDto> summaryDtos = new ArrayList<>();
            String timesId = getTimesId(lessonInfo);
            if (summaries != null && summaries.size() > 0) {
                for (LessonSummary lessonSummary : summaries) {
                    LessonSummaryDto summaryDto = new LessonSummaryDto();
                    summaryDto.setId(lessonSummary.getId());
                    summaryDto.setStudentId(lessonSummary.getStudentId());
                    summaryDto.setStudentName(lessonSummary.getStudentName());
                    summaryDto.setTeacherName(lessonSummary.getCreatorName());
                    summaryDto.setStatus(lessonSummary.getStatus());
                    //课前测
                    summaryDto.setEntranceScore(lessonSummary.getEntranceScore());
                    summaryDto.setHaveEntrance(getEntrance(timesId));
                    //课中练习
                    summaryDto.setPracticeScore(lessonSummary.getPracticeScore());
                    summaryDto.setHavePractice(getPractice(lessonInfo.getThirdId()));
                    //作业练习
                    summaryDto.setHomeworkScore(lessonSummary.getHomeworkScore());
                    summaryDto.setHaveHomework(getHomework(timesId));
                    //错题
                    summaryDto.setWrongTopicTotal(getWrongTopicTotal(lessonSummary.getLessonThirdId(), lessonSummary.getStudentId()));
                    summaryDto.setAttendance(lessonSummary.getAttendance());
                    summaryDto.setListenState(lessonSummary.getListenState());
                    summaryDto.setLastHomework(lessonSummary.getLastHomework());
                    summaryDto.setOutState(lessonSummary.getOutState());
                    summaryDto.setComment(lessonSummary.getComment());
                    summaryDto.setFilePath(lessonSummary.getFilePath());
                    //状态 小组课的设置在循环之前
                    if (type == 1) {
                        infoDto.setEvaluateStatus(lessonSummary.getStatus());
                    }
                    summaryDtos.add(summaryDto);
                }
//                infoDto.setSummaryDtos(summaryDtos);
            } else {
                //如果summaries为null则表示从未进入过学生评价列表界面，需要查询新舟的数据
                log.warn("调用新舟接口");
                summaryDtos = queryXzSchedule(lessonInfo, timesId);
            }
            infoDto.setSummaryDtos(summaryDtos);
            infoDtos.add(infoDto);

        }
        return xhPage;
    }


    /**
     * 准备条件
     *
     * @param bean
     * @param qw
     */
    private QueryWrapper prepareParams(LessonInfoRequest bean, QueryWrapper qw) {
        if (bean.getIds() != null && bean.getIds().length > 0) {
            qw.in("id", bean.getIds());
        }
        return qw;
    }

    private Integer getWrongTopicTotal(String lessonThirdId, String studentId) {
        QueryWrapper<LessonSummaryDetails> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("lesson_third_id", lessonThirdId);
        queryWrapper.eq("student_id", studentId);
        queryWrapper.eq("correct", 0);
        queryWrapper.groupBy("question_id");
        List<LessonSummaryDetails> lessonSummaryDetails = summaryDetailsService.queryByCondition(queryWrapper);
        Integer count = 0;
        if (!CollectionUtils.isEmpty(lessonSummaryDetails)) {
            count = lessonSummaryDetails.size();
        }
        return count;
    }

    /**
     * 获取timesId
     *
     * @param lessonInfo
     * @return java.lang.String
     * @author 赵文博
     * @date 2021/6/24 17:28
     **/
    private String getTimesId(LessonInfo lessonInfo) {
        QueryWrapper<LessonTimes> queryWrapper = new QueryWrapper();
        queryWrapper.eq("lesson_third_id", lessonInfo.getThirdId());
        LessonTimes lessonTimes = timesService.selectFirst(queryWrapper);
        return lessonTimes == null ? lessonInfo.getId() : lessonTimes.getId();
    }

    /**
     * 判断是否存在家庭作业
     *
     * @param timesId
     * @return boolean
     * @author 赵文博
     * @date 2021/6/25 10:12
     **/
    private boolean getHomework(String timesId) {
        QueryWrapper<LessonHomework> queryWrapper = new QueryWrapper();
        queryWrapper.eq("lesson_time_id", timesId);
        LessonHomework lessonHomework = homeworkService.selectFirst(queryWrapper);
        if (lessonHomework != null) {
            return true;
        }
        return false;
    }

    /**
     * 判断是否存在进门测
     *
     * @param timesId
     * @return boolean
     * @author 赵文博
     * @date 2021/6/25 10:12
     **/
    private boolean getEntrance(String timesId) {
        QueryWrapper<LessonEntranceExam> queryWrapper = new QueryWrapper();
        queryWrapper.eq("lesson_time_id", timesId);
        LessonEntranceExam entranceExam = examService.selectFirst(queryWrapper);
        if (entranceExam != null) {
            return true;
        }
        return false;
    }

    /**
     * 判断建议内是否有题
     *
     * @param thirdId
     * @return boolean
     * @author 赵文博
     * @date 2021/6/29 10:11
     **/
    private boolean getPractice(String thirdId) {
        LessonTimesRequest bean = new LessonTimesRequest();
        bean.setLessonThirdId(thirdId);
        return timesService.getPracticeQuestion(bean).size() > 0;
    }

    /**
     * 查询新舟数据
     *
     * @param lessonInfo
     * @return java.util.List
     * @author 赵文博
     * @date 2021/7/2 14:37
     **/
    private List<LessonSummaryDto> queryXzSchedule(LessonInfo lessonInfo, String timesId) {
        //查询排课学生
        XzScheduleRequest scheduleRequest = new XzScheduleRequest();
        if (1 == lessonInfo.getType()) {
            scheduleRequest.setStudentId(lessonInfo.getLessonId());
            scheduleRequest.setScheduleInstanceOTOType("一对一");
        } else {
            scheduleRequest.setGroupId(lessonInfo.getLessonId());
            scheduleRequest.setScheduleInstanceOTOType("一对六");
        }

        List<XzSchedule> schedules = xinzhouTmsService.querySchedule(scheduleRequest);

        Date startTime = lessonInfo.getStartTime();
        List<XzSchedule> stuList = schedules.stream().filter(schedule -> schedule.getClassDateTimeFrom().equals(startTime)).collect(Collectors.toList());
        stuList = stuList.stream().collect(collectingAndThen(toCollection(
                () -> new TreeSet<>(
                        Comparator.comparing(XzSchedule::getScheduleInstanceOTOId))), ArrayList::new));
        if (CollectionUtils.isEmpty(stuList)) {
            return Collections.EMPTY_LIST;
        }

        stuList = stuList.stream().sorted(Comparator.comparing(XzSchedule::getCreateTime)).collect(Collectors.toList());

        List<LessonSummaryDto> retList = new ArrayList();
        for (int i = 0; i < stuList.size(); i++) {
            XzSchedule xzSchedule = stuList.get(i);
            QueryWrapper qw=new QueryWrapper<LessonSummary>();
            qw.eq("lesson_id", lessonInfo.getId());
            qw.eq("lesson_third_id", lessonInfo.getThirdId());
            qw.eq("student_id", xzSchedule.getStudentId());

            Integer lessonSummary = summaryService.selectCount(qw);
            if (lessonSummary == 0) {
                LessonSummary summary = new LessonSummary();
                summary.setLessonId(lessonInfo.getId());
                summary.setStudentId(xzSchedule.getStudentId());
                summary.setLessonThirdId(lessonInfo.getThirdId());
                summary.setStudentName(xzSchedule.getStudentName());
                summary.setStatus(0);
                summary.setWrongTopicTotal(0);
                summaryService.insert(summary);
                LessonSummaryDto summaryDto = new LessonSummaryDto();
                BeanUtils.copyProperties(summary, summaryDto);
                //进门考
                summaryDto.setHaveEntrance(getEntrance(timesId));
                //课中练习
                summaryDto.setHavePractice(getPractice(lessonInfo.getThirdId()));
                //作业练习
                summaryDto.setHaveHomework(getHomework(timesId));
                retList.add(summaryDto);
            }
        }
        return retList;
    }
}
